﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Text;
using SharePointClient.SPWebService.Lists;

namespace SharePointClient
{
    public class ListCollection : WSSBase, IDisposable,IEnumerable<List>
    {
        List<List> lists = new List<List>();
        internal ListCollection(Connection connection,Uri url)
            : base(connection,url)
        {
            Refresh();
        }
        public override void Refresh()
        {
            Lists listsweb = new Lists();
            listsweb.Url = Uri + List.WebService;
            listsweb.Credentials = Credentials;
            ProgressEventArgs p = myConnection.DoProgress("Loading ListCollection from '" + Uri + "'");
            MetaDataElement = listsweb.GetListCollection();
            foreach (XmlNode n in Select("/wss:Lists/wss:List"))
            {
                List l;
                Guid gid=new Guid(Select(n,"@ID")[0].Value);
                if (myConnection.Cached(gid))
                {
                    l = (List) myConnection[gid];
                }
                else
                {
                    myConnection[gid]= l = new List(myConnection,Uri, n);
                }
                lists.Add(l);
            }
            p.Operation = "ListCollection from '" + Uri + "' loaded (" + lists.Count + ")";
            p.State = BeforeOrAfter.After;
            myConnection.UpdateProgress(p);
            
        
        }
        public int Count
        {
            get { return lists.Count; }
        }
        public List this[int pos]
        {
            get { return lists[pos]; }
        }
        public List this[string title]
        {
            get { title = title.ToLower(); foreach (List l in lists) if (title == l.Title.ToLower()) return l; return null; }
        }
        public List this[Guid listGuid]
        {
            get { foreach (List l in lists) if (listGuid == l.Guid) return l; return null; }
        }


        public override string ToString()
        {
            string slist = "";
            foreach (List l in lists)
                slist += ",\"" + l.Title + "\"";
            return slist.Substring(1);
        }


        #region IDisposable Member

        public void Dispose()
        {
            foreach (List l in lists) l.Dispose();
            lists.Clear();
        }

        #endregion

        #region IEnumerable<List> Member

        public IEnumerator<List> GetEnumerator()
        {
            return lists.GetEnumerator();
        }

        #endregion

        #region IEnumerable Member

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return lists.GetEnumerator();
        }

        #endregion
    }
}
